<template>
    <div class="editor">
        <b-form inline class="topForm px-4">
            <b-input-group
                class="w-50 b-input-h"
            >
                <label for="blogTitle">博客标题：</label>
                <b-input
                    id="blogTitle"
                    class="b-input-h"
                    placeholder="请输入博客标题"
                    v-model="article.title"
                    :state="validation"
                ></b-input>
            </b-input-group>
            <div class="a-rowArray uploadGroup">
                <b-button 
                    variant="primary"
                    class="submit mr-3"
                    @click="$refs['submit-container'].changeSubmit('open',article)"
                >提交博客</b-button>
                <b-form-file ref="fileInput" v-model="file2" class="fileInput" browse-text="浏览文件" placeholder="" accept="text/markdown"></b-form-file>
            </div>
        </b-form>
        <mavon-editor class="mavon-editor" 
        v-model="article.content"
        @imgAdd="imgAdd"
        @imgDel="imgDel"
        />
        <submit-modal ref="submit-container" />
    </div>
</template>

<script>
import SubmitModal from '@/components/editor/Submit'
import { pictureToken } from '@/../api/api.js'
import { getBlob } from '@/../api/index.js'
import Axios from 'axios';
import * as qiniu from 'qiniu-js';
import store from '@/store/index.js'
export default {
    components: {
        SubmitModal
    },
    data() {
        return {
            // 文章内容（带mark符号）
            article: {
                title:"",
                content:""
            },
            file2: [],
            validation: null,
            percent:1,
            isUpdate: false
        }
    },
    created() {
        if (store.state.editorArticle.article != null) {
            this.isUpdate = true;
            this.article.title = store.state.editorArticle.article.title;
            this.article.content = store.state.editorArticle.article.markdown;
        }
        if(sessionStorage.getItem("editorContent")) {
            this.article = Object.assign({}, JSON.parse(sessionStorage.getItem("editorContent")))
        }

        window.addEventListener("beforeunload", ()=> {
            sessionStorage.setItem("editorContent", JSON.stringify(this.article));
        });
    },
    methods:{
        imgAdd(pos,$file) {
            Axios.get(pictureToken)
            .then(Response => {
                if (Response.data.message == 'success') {
                    let file = getBlob($file.miniurl);
                        let config = {
                            useCdnDomain: true,   
                            region: null
                        };
                        let putExtra = {
                            fname: $file.name,  
                            params: {}, 
                            mimeType: ["image/png", "image/jpeg", "image/gif","image/jpg"]
                        };
                        let observable = qiniu.upload(file, $file.name, Response.data.data.token, putExtra, config);
                        observable.subscribe({
                            next: (result) => {
                                this.percent = parseInt(result.total.percent);
                            },
                            error: (errResult) => {
                                console.log(errResult);
                                window.alert('图片上传失败！');
                            },
                            complete: (result) => {
                                let url = 'http://img.sharpfactory.top/'+ result.key;
                                if (this.article.content.includes(name)) {
                                    let oStr = `(${pos})`;
                                    let nStr = `(${url})`;
                                    let index = this.article.content.indexOf(oStr);
                                    let str = this.article.content.replace(oStr, '');
                                    let insertStr = (soure, start, newStr) => {
                                        return soure.slice(0, start) + newStr + soure.slice(start);
                                    }
                                    this.article.content = insertStr(str, index, nStr);
                                }
                            }
                        });
                } else if(Response.data.message == 'tokenGuard') {
                    this.isShadow = false;
                    window.alert("已超过每天最大图片上传次数");
                }
            })
            .catch(err => {
                console.log(err);
            })
        },
        //没想好怎么操作
        imgDel(pos){
            // let oStr = `(${pos[0]})`;
            // let index = this.article.content.indexOf(oStr);
            // let str = this.article.content.replace(oStr, '');
            // let insertStr = (soure, start, newStr) => {
            //     return soure.slice(0, start) + newStr + soure.slice(start);
            // }
            // this.article.content = insertStr(str, index, '');
        }
    },
    watch: {
        file2: function(newValue, oldValue) {
            if(newValue.name && /\.md$/.test(newValue.name)){
                let reader = new FileReader();//新建一个FileReader
                reader.readAsText(newValue, "UTF-8");//读取文件 
                reader.onload = (evt) => { //读取完文件之后会回来这里
                    this.article.title = newValue.name.replace(/\.md$/, "")
                    this.article.content = evt.target.result; // 读取文件内容
                    this.validation = null;
                }
            }
            else {
                this.article.title = " 请导入.md格式文件";
                setTimeout(()=> {
                    this.validation = false;
                });
            }
        },
        article: {
            handler(newValue, oldValue) {
                this.validation = null;
            },
            deep: true
        }
    }
}
</script>

<style lang="stylus" scoped>
.topForm
    justify-content space-between
    padding 38px 0 12px
.b-input-h
    height 42px
    font-size 16px
#blogTitle
    color $base_color
    font-size 18px

.mavon-editor
    height 100vh
    margin 12px 8px 36px
    z-index 0
    
.uploadGroup
    width 320px
    .fileInput
        flex 1
        line-height 33px
        text-align left !important;
</style>